package com.jic.point.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jic.common.base.vo.PageResult;
import com.jic.point.constant.consist.ResponseCode;
import com.jic.point.exception.AppRuntimeException;
import com.jic.point.mapper.ConfActivityRuleApplyMapper;
import com.jic.point.mapper.ConfActivityRuleMapper;
import com.jic.point.mapper.ConfPlatformMapper;
import com.jic.point.model.entity.ConfActivityRule;
import com.jic.point.model.entity.ConfActivityRuleApply;
import com.jic.point.model.entity.ConfActivityRuleDetail;
import com.jic.point.rest.request.SignData;
import com.jic.point.service.ConfActivityRuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 接口实现类
 *
 * @author : tzc
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class ConfActivityRuleServiceImpl implements ConfActivityRuleService {

	@Resource
	private ConfActivityRuleMapper mapper;
	@Resource
	private ConfActivityRuleApplyMapper mapperApply;
	@Resource
	private ConfPlatformMapper confPlatformMapper;
	/**
	 * 新增记录
	 *
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存成功
	 */
	@Override
	public int save(ConfActivityRule request) {
	 int flag = mapper.insertSelective(request);
	 if (flag == 1) {
	   return 1;
	 }else {
	   throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
	 }
	}


	/**
	 * 保存或修改记录信息
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存或修改成功
	 * author tzc
	 * @date 2020-3-11 20:54:09
	 */
	@Override
	@Transactional
	public int saveOrUpdate(ConfActivityRule request){
		log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
		try {
			if (request == null) {
				throw new AppRuntimeException(ResponseCode.EXCEPTION,"入参为空");
			}
			if (request.getId() != null) {
				log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
				//修改数据，获取到 活动表后，主表逻辑删除
				ConfActivityRule ConfActivityRule  = new ConfActivityRule();
				ConfActivityRule.setDeleteFlag(1);
				ConfActivityRule.setId(request.getId());
				int flag = mapper.updateByPrimaryKey(ConfActivityRule);
				//判断积分是否做了改变
	  			ConfActivityRule confActivityRuleUpdate = mapper.selectByPrimaryKey(ConfActivityRule);
				//比较修改后的 总积分 和 修改前的总积分是否一样
				if(confActivityRuleUpdate.getTotal().compareTo(request.getTotal())!=0){
					//查询相差 负数代表 积分下调 正数代表积分上调
					BigDecimal subtract = request.getTotal().subtract(confActivityRuleUpdate.getTotal());
					//修改绑定平台的积分
					ConfActivityRule confActivity = new ConfActivityRule();
					BeanUtils.copyProperties(request,confActivity);
					confActivity.setAvailable(subtract);
					confActivity.setDescription("活动修改总积分");
					if(subtract.signum()==1){ confActivity.setType(1); }else { confActivity.setType(2); }
					// 修改平台积分
					int i = confPlatformMapper.activityRuleDeductionPoints(confActivity);
					if (i < 1)  throw new AppRuntimeException(ResponseCode.ELSE_REEOE,"请保证积分是否充足！");
					//积分冻结成功，插入积分流水表中
					int i1 = mapper.insertActiveRuleLog(confActivity);
					if(subtract.signum()==1){ confActivity.setType(3); }else { confActivity.setType(4); }
					//积分冻结插入平台流水表中delete
					int i2 = confPlatformMapper.insertPlatFromLog(confActivity);
				}
				//主表逻辑删除后，新增至申请表
				request.setCurrentAction(1);
				request.setId(null);
				ConfActivityRuleApply confActivityRuleApply = new ConfActivityRuleApply();
				BeanUtils.copyProperties(request,confActivityRuleApply);
				//判断  如果积分修改了  更改活动总积分 和 可用积分
				if(confActivityRuleUpdate.getTotal().compareTo(request.getTotal())!=0){
					BigDecimal subtract = request.getTotal().subtract(confActivityRuleUpdate.getTotal());//查询相差 负数代表 积分下调 正数代表积分上调
					confActivityRuleApply.setAvailable(confActivityRuleApply.getAvailable().add(subtract));
					confActivityRuleApply.setLimited(confActivityRuleApply.getAvailable().add(subtract));
				}
				int i = mapperApply.insertSelective(confActivityRuleApply);

				if(flag == 1){
					return 1;
				}
			}else{
				log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
				request.setCreator(request.getAdminOperate().getOperator());
				int flag = mapper.insertSelective(request);
				if(flag == 1){
				  return 1;
				}else{
				  throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改失败");
				}
			}
		} catch (Exception e) {
			log.error("用户保存或修改失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"用户保存或修改失败");
		}
	     return -1;
	}

    @Override
    public int saveOrUpdateApply(ConfActivityRule request) {
        log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
        try {
            if (request == null) {
                throw new AppRuntimeException(ResponseCode.EXCEPTION,"入参为空");
            }
            if (request.getId() != null) {
                log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
                int flag = mapper.updateByPrimaryKeyApply(request);
                if(flag == 1){
                    return 1;
                }
            }
        } catch (Exception e) {
            log.error("用户保存或修改失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION,"用户保存或修改失败");
        }
        return -1;
    }

    /**
	 * 删除记录
	 *
	 * @param request 需要删除,含有主键的入参实体类
	 * @return int 是否删除成功
	 */
	@Override
	public int deleteByPrimaryKey(ConfActivityRule request) {
		request.setDeleteFlag(1);
		int flag = mapper.deleteByPrimaryKey(request);
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
	    }
	}


	/**
	 * 逻辑删除记录
	 *
	 * @param request 含有主键的逻辑删除实体类
	 * @return int 是否逻辑删除成功
	 */
	@Override
	@Transactional
	public int deleteByPrimaryKeyLogically(ConfActivityRule request) {
		//主表逻辑删除
		ConfActivityRuleApply confActivityRuleApply = new ConfActivityRuleApply();
		request.setCurrentAction(2);
		BeanUtils.copyProperties(request,confActivityRuleApply);
		confActivityRuleApply.setId(null);
		int i = mapperApply.insertSelective(confActivityRuleApply);
		if(i<1){
			throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增申请表失败");
		}
		request.setDeleteFlag(1);
		int flag = mapper.updateByPrimaryKey(request);
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "逻辑删除记录失败");
	    }
	}


	/**
	 * 修改
	 *
	 * @param request
	 * @return
	 */
	@Override
	public int updateByPrimaryKeySelective(ConfActivityRule request){
		try {
			log.info("修改记录");
			int flag = mapper.updateByPrimaryKeySelective(request);
	        if (flag == 1) {
	         return 1;
	        }else {
	          throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
	        }
		} catch (Exception e) {
			log.error("修改记录失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改记录失败");
		}

	}

	/**
	 * 记录详情
	 *
	 * @param request 查询的入参实体类
	 * @return 数据库查询到的实体类
	 */
	@Override
	public ConfActivityRule getByPrimaryKey(ConfActivityRule request) {
		return mapper.selectByPrimaryKey(request);
	}


	/**
	 * 分页查询
	 *
	 * @param request 分页查询入参实体类
	 * @return 含有分页信息的实体类列表
	 */
	@Override
	public PageInfo<ConfActivityRule> listPageBySelective(ConfActivityRule request, int pageNum, int pageSize) {
	PageHelper.startPage(pageNum, pageSize);
	PageHelper.orderBy(" create_time desc");
	List<ConfActivityRule> list = mapper.listPageBySelective(request);
	PageInfo pageInfo = new PageInfo(list);
	PageResult<ConfActivityRule> result = new PageResult<>();
	result.setTotal(pageInfo.getTotal());
	result.setRows(list);
	return new PageInfo(list);
	}
	@Override
	public PageInfo<ConfActivityRule> listPageBySelectivefreeze(ConfActivityRule request, int pageNum, int pageSize) {
		List<Integer> sts=new ArrayList<>();
		sts.add(-3);
		sts.add(-2);
		sts.add(2);
		PageHelper.startPage(pageNum, pageSize);
		PageHelper.orderBy(" create_time desc");
		List<ConfActivityRule> list = mapper.listPageBySelectivefreeze(sts);
		PageInfo pageInfo = new PageInfo(list);
		PageResult<ConfActivityRule> result = new PageResult<>();
		result.setTotal(pageInfo.getTotal());
		result.setRows(list);
		return new PageInfo(list);
	}

	/**
	 * 不分页查询
	 *
	 * @param request 不分页查询入参实体类
	 * @return 数据库查到的实体类列表
	 */
	@Override
	public List<ConfActivityRule> listAllRecord(ConfActivityRule request) {
		//分页处理
		request.setDeleteFlag(0);
		return mapper.selectBySelective(request);
	}

	@Override
	public int insertActiveRuleLog(ConfActivityRule confActivityRule) {
		return mapper.insertActiveRuleLog(confActivityRule);
	}

	@Override
	public List<ConfActivityRule> selConfActivityRuleByCode(SignData signData) {
		return  mapper.selConfActivityRuleByCode(signData);
	}

	@Override
	public int deleteFlagActivityRule(ConfActivityRule confActivityRule) {
		return mapper.deleteFlagActivityRule(confActivityRule);
	}

	@Override
	public int updateByCode(ConfActivityRule param) {
		return mapper.updateByCode(param);
	}

	@Override
	public List<ConfActivityRuleDetail> selDetailList(ConfActivityRuleApply result) {
		return mapper.selDetailList(result);
	}

	@Override
	public int ActivityPointAdd(ConfActivityRule confActivityRule) {
		return mapper.ActivityPointAdd(confActivityRule);
	}


}
